package com.hibase.core.mybatis.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hibase.common.util.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

/**
 * @author chenfeng
 * @version 1.0
 * @date 2021/11/3 14:24
 * @des https://gitee.com/cheershi
 */
@Slf4j
public class HibaseMetaObjectHandler implements MetaObjectHandler {

    private static final String DEFAULT_NAME = "SYSTEM";

    @Override
    public void insertFill(MetaObject metaObject) {
        //自动插入时间
        log.debug("insertFill running....");
        // setFieldValByName（自动填充的字段，填充的值，metaObject）
//        if(metaObject.hasGetter("id")){
//            this.setFieldValByName("id", GenerateIdHelper.idGenerate(),metaObject);
//        }
        if(metaObject.hasGetter("createBy")){
            this.setFieldValByName("createBy",
                    ObjectUtil.isEmpty(UserContext.get())?DEFAULT_NAME: UserContext.get().getLoginName(),
                    metaObject);
        }
        if(metaObject.hasGetter("createTime")){
            this.setFieldValByName("createTime", DateUtil.date(),metaObject);
        }
        if(metaObject.hasGetter("updateBy")){
            this.setFieldValByName("updateBy",
                    ObjectUtil.isEmpty(UserContext.get())?DEFAULT_NAME: UserContext.get().getLoginName(),
                    metaObject);
        }
        if(metaObject.hasGetter("updateTime")){
            this.setFieldValByName("updateTime", DateUtil.date(),metaObject);
        }
        if(metaObject.hasGetter("beDeleted")){
            this.setFieldValByName("beDeleted", Boolean.FALSE,metaObject);
        }

        if(metaObject.hasGetter("version")){
            this.setFieldValByName("version", 0, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("updateFill running....");
        if(metaObject.hasGetter("updateBy")){
            this.setFieldValByName("updateBy",
                    ObjectUtil.isEmpty(UserContext.get())?DEFAULT_NAME: UserContext.get().getLoginName(),
                    metaObject);
        }
        if(metaObject.hasGetter("updateTime")){
            this.setFieldValByName("updateTime",DateUtil.date(),metaObject);
        }
    }
}
